import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style// get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = store.getters.token
  if (hasToken) {
    if (to.path === '/login') {
      NProgress.done()
      next('/')
    } else {
      NProgress.done()
      if (!store.getters.userId) {
        await store.dispatch('user/getUserInfo')
      }
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      NProgress.done()
      next('/login')
    }
  }
})

router.afterEach((to, from) => {
  // finish progress bar
  NProgress.done()
  // console.log('from', from)
  // console.log('to', to) // to 里面包含路由元信息 以及路由参数
  document.title = `pperson后台管理系统-${to.meta?.title}`
})
